/**
 * 微信设置分析路由，（功能不完善，好像当时未实现）
 */

var router = require('express').Router();
var assertAlljs = require('../bin/util/assert-alljs');
var redisentity = require('../bin/redisentity');
var requestPromise = require('../bin/driver/requestPromise');
var wechatConfig = require('../bin/getConfig')('config/wechat.json');
var wechatSign = require('../bin/driver/wechatsign');

router.post('/wechatConfig', async function(req, res){
    let assert = assertAlljs(req, res);
    if (await assert(!req.body.url))
        return;

    let appId = wechatConfig.appId;
    let appSecret = wechatConfig.appSecret;

    try{
        var jsapi_ticket = await redisentity.get('var', 'wechatticket');
        if (!jsapi_ticket){
            var access_token = await redisentity.get('var', 'wechattoken');
            if (!access_token){
                var tokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+appId+'&secret='+appSecret;
                let {response, body} = await requestPromise(tokenUrl);
                if (typeof(body) !== 'string')
                    throw new Error();
                body = JSON.parse(body);
                access_token = body.access_token;
                await redisentity.set('var', 'wechattoken', access_token, 7200000);
            }

            var ticketUrl = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+access_token+'&type=jsapi';
            let {response, body} = await requestPromise(ticketUrl);
            if (typeof(body) !== 'string')
                throw new Error();
            body = JSON.parse(body);
            jsapi_ticket = body.ticket;
            await redisentity.set('var', 'wechatticket', jsapi_ticket, 7200000);
        }
    }catch (err){
        res.json({success:false, msg:'get wechat-ticket faild:' + err.message, result:null});
    }
    try{
        let debug = false;
        let jsApiList = ['updateAppMessageShareData', 'updateTimelineShareData', 'onMenuShareTimeline',  'onMenuShareAppMessage', 'onMenuShareQQ'];
        let signObj = wechatSign(debug, appId, jsApiList, jsapi_ticket, req.body.url);
        res.json({success:true,config:signObj});
    }catch (err){
        res.json({success:false, msg:'get wechat-sign faild:' + err.message, result:null});
    }
});

module.exports = router;